package com.heima.comment.service.impl;

import com.heima.comment.pojo.ApComment;
import com.heima.comment.pojo.ApCommentLike;
import com.heima.comment.pojo.ApCommentRepay;
import com.heima.comment.service.CommentRepayService;
import com.heima.feign.article.IArticleClient;
import com.heima.feign.user.IUserClient;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dto.CommentRepayDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.nntp.Article;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @projectName: leadnews-project
 * @package: com.heima.comment.service.impl
 * @className: CommentRepayServiceImpl
 * @author: Eric
 * @description: TODO
 * @date: 2024/1/25 19:26
 * @version: 1.0
 */
@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IUserClient iuserClient;
    @Autowired
    private IArticleClient articleClient;
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //1.检查参数
        if(dto == null || dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        int size = 5;
        //2.加载数据
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime")).limit(size);
        List<ApCommentRepay> list = mongoTemplate.find(query, ApCommentRepay.class);

        //3.判断用户登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.okResult(list);
        }

        //需要查询当前评论中哪些数据被点赞了
        List<String> idList = list.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query1, ApCommentRepay.class);
        if (apCommentRepays == null) {
            return ResponseResult.okResult(list);
        }

        List<ApCommentRepay> resultList = new ArrayList<>();
        list.forEach(acr -> {
            ApCommentRepay ac = new ApCommentRepay();
            BeanUtils.copyProperties(acr, ac);
            for (ApCommentRepay apCommentRepay1 : apCommentRepays) {
                if (acr.getId().equals(apCommentRepay1.getCommentId())) {
                    ac.setOperation((short) 0);
                    break;
                }
            }
            resultList.add(ac);
        });

        return ResponseResult.okResult(resultList);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepayDto dto) {
        //1.检查参数
        if(dto == null || StringUtils.isBlank(dto.getContent()) || dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判定评论字数不能超过50个字
        if(dto.getContent().length() > 140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容不能超过140字");
        }
        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUser dbUser = iuserClient.findUserById(user.getId());
        if(dbUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前登录信息有误");
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setAuthorName(dbUser.getName());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.save(apCommentRepay);

        //5更新回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        assert apComment != null;
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);
        articleClient.addComment(apComment.getEntryId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult likeCommentRepay(CommentRepayDto dto) {
        //1.检查参数
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        //3.点赞：0点赞  1 取消点赞
        if (apComment !=null && dto.getOperation()==0){
            //更新评论点赞数量 点赞数量加1
            apComment.setLikes(apComment.getLikes()+1);
            mongoTemplate.save(apComment);

            //保存评论点赞数据
            ApCommentLike apCommentLike=new ApCommentLike();
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentLike);
        }else if (dto.getOperation()==1){
            //更新点赞数量
            assert apComment != null;
            int tmp= apComment.getLikes()-1;
            tmp =tmp < 1 ? 0 : tmp;
            apComment.setLikes(tmp);
            mongoTemplate.save(apComment);
            //删除评论点赞
            Query query = Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(user.getId()));
            mongoTemplate.remove(query, ApCommentLike.class);
        }
        //4.取消点赞
        Map<String,Object> result=new HashMap<>();
        result.put("likes",apComment.getLikes());
        return ResponseResult.okResult(result);
    }
}
